package com.mxnet.chongjin.supoman.activity;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.adapter.LvRepairRecordAdapter;
import com.mxnet.chongjin.supoman.bean.RepairRecord;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class RepairRecordActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private Context mContext;
    private LinearLayout mLinearLayout;
    private LvRepairRecordAdapter mAdapter;
    private ListView mListView;
    private List<RepairRecord> mList;
    private SharedPreferences mPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repair_record);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mContext = RepairRecordActivity.this;
        mPreferences = getSharedPreferences("supoman", MODE_PRIVATE);

        initView();
        initData();
    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_repair_record);
        mLinearLayout.setOnClickListener(this);

        mListView = findViewById(R.id.lv_repair_record);
        mListView.setOnItemClickListener(this);
    }

    public void initData() {
        mList = new ArrayList();
        OkHttpUtils.get()
                .url(Api.URL_HEADER + Api.DECLARATIONFORM)
                .addParams("userId", mPreferences.getString("userId", ""))
                .addParams("pageNum", "0")
                .addParams("pageSize", "100")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean success = jsonObject.optBoolean("success");
                                if (success) {
                                    JSONArray data = jsonObject.optJSONArray("data");
                                    for (int i = 0; i < data.length(); i++) {
                                        RepairRecord record = new RepairRecord();
                                        JSONObject object = data.optJSONObject(i);
                                        record.setCountry(object.optString("country"));
                                        record.setZipCode(object.optString("zipCode"));
                                        record.setRobotNo(object.optString("robotNo"));
                                        record.setSalerName(object.optString("salerName"));
                                        record.setDeclarationMemo(object.optString("declarationMemo"));
                                        record.setCity(object.optString("city"));
                                        record.setDeclarationNo(object.optString("declarationNo"));
                                        record.setCustomerName(object.optString("customerName"));
                                        record.setRobotImgUrl(object.optString("robotImgUrl"));
                                        RepairRecord.ImgResourceBean imgResourceBean = new RepairRecord.ImgResourceBean();
                                        JSONObject object1 = object.optJSONObject("imgResource");
                                        imgResourceBean.setCreateTime(object1.optLong("createTime"));
                                        imgResourceBean.setFileType(object1.optString("fileType"));
                                        imgResourceBean.setId(object1.optString("id"));
                                        imgResourceBean.setMd5(object1.optString("md5"));
                                        imgResourceBean.setName(object1.optString("name"));
                                        imgResourceBean.setSize(object1.optString("size"));
                                        imgResourceBean.setType(object1.optString("type"));
                                        imgResourceBean.setUrl(object1.optString("url"));
                                        imgResourceBean.setUserId(object1.optString("userId"));
                                        record.setImgResource(imgResourceBean);
                                        record.setProjectNo(object.optString("projectNo"));
                                        record.setDistirct(object.optString("distirct"));
                                        record.setCreateTime(object.optLong("createTime"));
                                        record.setSalerNo(object.optString("salerNo"));
                                        record.setDetailAddress(object.optString("detailAddress"));
                                        record.setDeclarationStatus(object.optString("declarationStatus"));
                                        record.setId(object.optString("id"));
                                        record.setCustomerMobile(object.optString("customerMobile"));
                                        JSONArray maintenanceRecords = object.optJSONArray("maintenanceRecords");
                                        List<RepairRecord.MaintenanceRecordsBean> maintenanceRecordsBeanList = new ArrayList<>();
                                        for (int j = 0; j < maintenanceRecords.length(); j++) {
                                            RepairRecord.MaintenanceRecordsBean recordsBean = new RepairRecord.MaintenanceRecordsBean();
                                            JSONObject object2 = maintenanceRecords.optJSONObject(j);
                                            recordsBean.setChangePartsList(object2.optString("changePartsList"));
                                            recordsBean.setCreateTime(object2.optLong("createTime"));
                                            recordsBean.setDeclarationNo(object2.optString("declarationNo"));
                                            recordsBean.setId(object2.optString("id"));
                                            recordsBean.setMaintenanceMemo(object2.optString("maintenanceMemo"));
                                            recordsBean.setMaintenanceTime(object2.optLong("maintenanceTime"));
                                            JSONArray jsonArray = object2.optJSONArray("resourceIdList");
                                            List<String> list = new ArrayList<>();
                                            for (int k = 0; k < jsonArray.length(); k++) {
                                                list.add(jsonArray.optString(k));
                                            }
                                            recordsBean.setResourceIdList(list);
                                            maintenanceRecordsBeanList.add(recordsBean);
                                        }
                                        record.setMaintenanceRecords(maintenanceRecordsBeanList);
                                        mList.add(record);
                                        mAdapter = new LvRepairRecordAdapter(mContext, mList);
                                        mListView.setAdapter(mAdapter);
                                    }
                                } else {
                                    ToastUtils.showToast(mContext, jsonObject.optString("msg"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_repair_record:
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        intent.setClass(mContext, RepairDetailActivity.class);
        RepairRecord repairRecord = (RepairRecord) parent.getAdapter().getItem(position);
        Bundle bundle = new Bundle();
        bundle.putParcelable("record", repairRecord);
        intent.putExtras(bundle);
        mContext.startActivity(intent);
    }
}
